package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.DateFormatUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.form.service.impl.ScriptImpl;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WFadongji;
import com.ccp.dev.qbdms.service.WFadongjiService;
import com.ccp.dev.qbdms.service.WQbdFalProblemresetService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import com.ccp.dev.system.service.SysOrgService;
import com.ccp.dev.system.service.SysUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 发动机试车 信息操作处理控制器
 *
 * @author sun
 * @date 2020-06-08 13:45:02
 */
@Controller
@Action(customModel = "发动机试车")
@RequestMapping("/qbdms/wFadongji")
public class WFadongjiController extends SysBaseController{
	@Resource
	private WFadongjiService wFadongjiService;
    @Resource
    private ScriptImpl scriptImpl;
    @Resource
    private WQbdFalProblemresetService wQbdFalProblemresetService;
    @Resource
    private SysOrgService sysOrgService;
    @Resource
    private SysUserService sysUserService;

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: sun
     * @date: 2020-06-08 13:45:02
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到发动机试车首页", exectype = "页面跳转日志")
    public String viewList(Model model) {
        model.addAttribute("currentUserId", scriptImpl.getCurrentUserId());
        //2020/6/9 zzy 根据系统登记切换不同的台账列表页 如果集团则跳转集团对应的台账页, 院和所级用同一个
        if (BaseUtil.getCurrentSystemLevel().equals(BaseUtil.SystemLevel.GROUPLEVEL)) {
            // 传入数据来源下来选项
            wQbdFalProblemresetService.getOriginOrgToDicList();
            model.addAttribute("originOrgList", JSON.toJSONString(wQbdFalProblemresetService.getOriginOrgToDicList()));
            return "wFadongji/list_jituan";
        }
        return "wFadongji/list";
    }

    /**
    * 功能描述: 附带检索条件的分页查询
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: sun
    * @date: 2020-06-08 13:45:02
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询发动机试车",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        //2020/6/8 zzy 默认排序 试车时间倒序排序
        queryFilter.put("orderField", "sjrq");
        queryFilter.put("orderSeq", "desc");
        ZhiLiangConst.addQueryFilter(queryFilter);
        //分页数据
        List<WFadongji> pageDatas = wFadongjiService.queryList(queryFilter);
        //2020/6/8 zzy 处理信息状态
        //for (WFadongji pageData : pageDatas) {
        //    pageData.setReportStatusStr(ZhiLiangConst.getStatusStrByInt(pageData.getReportStatus()));
        //    if (StringUtil.isNotEmpty(pageData.getFilldeptid())) {
        //        pageData.setFilldept(sysOrgService.getSysOrgByOrgCode(pageData.getFilldeptid()).getOrgName());
        //    }
        //    if (StringUtil.isNotEmpty(pageData.getFilldeptHospitalId())) {
        //        pageData.setFilldepthospital(sysOrgService.getSysOrgByOrgCode(pageData.getFilldeptHospitalId()).getOrgName());
        //    }
        //    pageData.setFillman(sysUserService.getByAccount(pageData.getFillmanaccount()).getFullName());
        //}
        ZhiLiangConst.showName(pageDatas);
        //2020/6/9 zzy 配置数据是否允许编辑
        ZhiLiangConst.isDataAllowEdit(pageDatas, false);

        SysAuditThreadLocalHolder.putParamerter("success",true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: sun
     * @date: 2020-06-08 13:45:02
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到发动机试车新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        //2020/6/24 zzy 要求在编辑页上增加填报信息
        if (StringUtil.isEmpty(id)) {
            modelMap.put("filldate", DateFormatUtil.format(new Date()));
            modelMap.put("filldept", scriptImpl.getCurrentOrgName());
            modelMap.put("fillman", scriptImpl.getCurrentName());
        }
        return "wFadongji/add";
    }

    /**
    * 功能描述:  数据保存通用方法
    *
    * @param: wFadongji 保存的对象
    * @return: java.lang.Object
    * @auther: sun
    * @date: 2020-06-08 13:45:02
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存发动机试车数据",detail="<#if isAdd>新增<#else>编辑</#if>发动机试车数据<#if success>成功<#else>失败</#if><#if StringUtil.isNotEmpty(modifyInfo)>${modifyInfo}</#if>")
    public Object save(@RequestBody WFadongji wFadongji) {
        String id = wFadongji.getId();
        int result;
        wFadongji.setBelongdeptname(BaseUtil.getCurrentTenOrgCodePath());
        Date d = new Date();
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd",true);
            ZhiLiangConst.addCommonFields(wFadongji);
            //上报状态
            wFadongji.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());
            wFadongji.setId(ProjectUUIDUtils.getUUIDFor32());
            //处理通用字段
            ZhiLiangConst.addCommonFields(wFadongji);
            result = wFadongjiService.add(wFadongji);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            ZhiLiangConst.updateCommonFields(wFadongji);
            //修改操作
            SysAuditThreadLocalHolder.putParamerter("modifyInfo", StructureModifyUtil.getModifyInfo(wFadongjiService.getOneById(id), wFadongji));
            result = wFadongjiService.update(wFadongji);
        }
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
    * 功能描述: 跳转到详情页面
    *
    * @return: java.lang.String
    * @auther: sun
    * @date: 2020-06-08 13:45:02
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到发动机试车详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        String isClose = RequestUtil.getString(request, "isClose");
        modelMap.put("id",id);
        modelMap.put("isClose", isClose);
        modelMap.put("systemLevel", BaseUtil.getCurrentSystemLevel());
        //2020/6/9 zzy 抓取一下dof 数据来源标记,表示数据是否来自6院,如果为6院则跳转到6院对应的详情页
        String dof=RequestUtil.getString(request, "dof","");
        if (StringUtil.isNotEmpty(dof) && ZhiLiangConst.FDJSC_DOF_6.equals(dof)) {
            return "wFadongji/particulars_liuyuan";
        }
        return "wFadongji/particulars";
    }

    /**
    * 功能描述: 根据主键id获取一条数据的通用查询方法
    *
    * @param: id 参数对象必须是"id"
    * @return: java.lang.Object
    * @auther: sun
    * @date: 2020-06-08 13:45:02
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询发动机试车的一条数据",detail="根据主键id查询发动机试车的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WFadongji wFadongji = wFadongjiService.getOneById(id);
        if (null == wFadongji) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        //if (StringUtil.isNotEmpty(wFadongji.getFilldeptid())) {
        //    wFadongji.setFilldept(sysOrgService.getSysOrgByOrgCode(wFadongji.getFilldeptid()).getOrgName());
        //}
        //if (StringUtil.isNotEmpty(wFadongji.getFilldeptHospitalId())) {
        //    wFadongji.setFilldeptHospital(sysOrgService.getSysOrgByOrgCode(wFadongji.getFilldeptHospitalId()).getOrgName());
        //}
        //SysUser fillman = sysUserService.getByAccount(wFadongji.getFillmanaccount());
        //if (BeanUtils.isNotEmpty(fillman)) {
        //    wFadongji.setFillman(fillman.getFullName());
        //}
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",wFadongji);
    }

    /**
    * 功能描述: 根据主键ID删除数据的通用删除方法
    *
    * @param: id 参数名称必须是"id"
    * @return: java.lang.Object
    * @auther: sun
    * @date: 2020-06-08 13:45:02
    */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除发动机试车数据",exectype = "删除日志",detail="删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) {
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail("delete.failure.message");
        }
        //2020/6/10 zzy 判断数据是否允许删除
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WFadongji data = wFadongjiService.getOneById(key);
            if (Objects.nonNull(data.getReportStatus())
                    && !"11".equals(data.getReportStatus())
                    && !"4".equals(data.getReportStatus())
            ) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只允许删除待上报、无需上报、院内待审批的数据");
            }
            if (!userId.equals(data.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只能删除自己创建的数据！");
            }
        }
        int result = wFadongjiService.delByIdArray(id.split(","));
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }


    /**
     * 功能描述: 跳转到导出选择字段页面
     *
     * @return: java.lang.String
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description="跳转到发动机试车信息导出选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request,ModelMap modelMap) throws Exception {
        JSONObject jsonObject = AuxiliaryUtil.resolverModel(WFadongji.class);
        modelMap.put("tableInfo",jsonObject.toString());
        return "expImp/add";
    }


    /**
    * 功能描述: 导出发动机试车数据信息
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: sun
    * @date: 2020-06-08 13:45:02
    */
    @RequestMapping("/exportData")
    @Action(description="导出发动机试车数据信息",detail="导出发动机试车数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter, id);
        List<WFadongji> wFadongjiList = this.wFadongjiService.queryAll(queryFilter);
        if (wFadongjiList.isEmpty()) {
            wFadongjiList.add(new WFadongji());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request, response, wFadongjiList, dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }


    /**
     * 查询上报的信息
     *
     * @param request
     * @param id
     * @param tableName
     * @return
     */
    @RequestMapping("/reportList")
    @ResponseBody
    public Object reportList(HttpServletRequest request, @RequestParam("id") String id, @RequestParam("tableName") String tableName) {
        //业务数据
        List<WFadongji> reportList = wFadongjiService.reportList(id, tableName);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        //for (WFadongji wFadongji : reportList) {
        //    if (StringUtil.isNotEmpty(wFadongji.getFilldeptid())) {
        //        wFadongji.setFilldept(sysOrgService.getSysOrgByOrgCode(wFadongji.getFilldeptid()).getOrgName());
        //    }
        //    if (StringUtil.isNotEmpty(wFadongji.getFilldeptHospitalId())) {
        //        wFadongji.setFilldeptHospital(sysOrgService.getSysOrgByOrgCode(wFadongji.getFilldeptHospitalId()).getOrgName());
        //    }
        //    wFadongji.setFillman(sysUserService.getByAccount(wFadongji.getFillmanaccount()).getFullName());
        //}
        return getResultDataSuccess("options.success", reportList);
    }

}
